import 'dart:developer' as developer;
import 'dart:convert';
import 'package:flutter/material.dart';
import '../models/user_model.dart';
import '../repositories/auth_repository.dart';
import '../errors/error_handler.dart';
import '../services/error_logger_service.dart';
import '../services/websocket_service_rust.dart';
import '../services/call_manager_service.dart';
import '../di/service_locator.dart';
import 'contacts_viewmodel.dart';
import 'home_viewmodel.dart';
import '../../shared/storage/storage_service.dart';

class AuthViewModel extends ChangeNotifier {
  final AuthRepository _authRepository;
  WebSocketServiceRust? _webSocketService;

  AuthViewModel(this._authRepository);

  /// 设置 WebSocket 服务（用于退出时断开连接）
  void setWebSocketService(WebSocketServiceRust webSocketService) {
    _webSocketService = webSocketService;
  }

  bool _isLoading = false;
  String? _errorMessage;
  UserModel? _currentUser;

  bool get isLoading => _isLoading;
  String? get errorMessage => _errorMessage;
  UserModel? get currentUser => _currentUser;
  bool get isLoggedIn => _currentUser != null;

  Future<bool> login({
    required String username,
    required String password,
  }) async {
    _isLoading = true;
    _errorMessage = null;
    notifyListeners();

    try {
      final response = await _authRepository.login(
        username: username,
        password: password,
      );

      _isLoading = false;

      if (response.success && response.data != null) {
        _currentUser = response.data;
        _errorMessage = null;
        notifyListeners();
        
        // 登录成功后连接 WebSocket（用于接收推送消息）
        try {
          await _webSocketService?.connect();
          developer.log('✅ WebSocket connected after login', name: 'AuthViewModel');
        } catch (e) {
          developer.log('⚠️ Failed to connect WebSocket after login: $e', name: 'AuthViewModel');
          // WebSocket 连接失败不影响登录成功，只记录日志
        }
        
        // 刷新全局通话管理服务的好友列表和用户ID
        try {
          final callManagerService = CallManagerService();
          await callManagerService.refreshFriends();
          developer.log('✅ CallManagerService refreshed after login', name: 'AuthViewModel');
        } catch (e) {
          developer.log('⚠️ Failed to refresh CallManagerService after login: $e', name: 'AuthViewModel');
          // 不影响登录成功
        }
        
        return true;
      } else {
        _errorMessage = response.message;
        notifyListeners();
        return false;
      }
    } catch (e) {
      _isLoading = false;
      _errorMessage = ErrorHandler.getErrorMessage(e);
      ErrorLoggerService.logError(e, context: 'Login');
      notifyListeners();
      return false;
    }
  }

  Future<bool> register({
    required String username,
    required String password,
    String? email,
    String? phone,
  }) async {
    _isLoading = true;
    _errorMessage = null;
    notifyListeners();

    try {
      final response = await _authRepository.register(
        username: username,
        password: password,
        email: email,
        phone: phone,
      );

      _isLoading = false;

      if (response.success && response.data != null) {
        _currentUser = response.data;
        _errorMessage = null;
        notifyListeners();
        return true;
      } else {
        _errorMessage = response.message;
        notifyListeners();
        return false;
      }
    } catch (e) {
      _isLoading = false;
      _errorMessage = ErrorHandler.getErrorMessage(e);
      ErrorLoggerService.logError(e, context: 'Register');
      notifyListeners();
      return false;
    }
  }

  Future<void> logout() async {
    _isLoading = true;
    _errorMessage = null;
    notifyListeners();

    try {
      // 1. 断开 WebSocket 连接
      _webSocketService?.disconnect();
      
      // 2. 清理其他 ViewModel 的数据
      final serviceLocator = ServiceLocator();
      serviceLocator.contactsViewModel.clear();
      serviceLocator.homeViewModel.clear();
      
      // 3. 调用 repository 的 logout，清理所有存储数据
      await _authRepository.logout();
      
      // 4. 清理本地状态
      _currentUser = null;
      _errorMessage = null;
      _isLoading = false;
      notifyListeners();
    } catch (e) {
      _isLoading = false;
      _errorMessage = ErrorHandler.getErrorMessage(e);
      ErrorLoggerService.logError(e, context: 'Logout');
      notifyListeners();
    }
  }

  Future<void> checkLoginStatus() async {
    final isLoggedIn = await _authRepository.isLoggedIn();
    if (!isLoggedIn) {
      _currentUser = null;
      notifyListeners();
    } else {
      // 如果已登录，尝试从存储中恢复用户信息
      await restoreUserFromStorage();
    }
  }

  /// 从存储中恢复用户信息
  Future<void> restoreUserFromStorage() async {
    try {
      // 检查是否有 token
      final isLoggedIn = await _authRepository.isLoggedIn();
      developer.log('🔍 Checking login status: $isLoggedIn', name: 'AuthViewModel');
      
      if (!isLoggedIn) {
        developer.log('❌ No token found, clearing user', name: 'AuthViewModel');
        _currentUser = null;
        notifyListeners();
        return;
      }

      // 从存储中获取用户信息
      final storageService = StorageService();
      final userInfoJson = await storageService.getUserInfo();
      
      developer.log('📦 User info from storage: ${userInfoJson != null ? "Found (${userInfoJson.length} chars)" : "Not found"}', name: 'AuthViewModel');
      
      if (userInfoJson != null && userInfoJson.isNotEmpty) {
        try {
          // 解析 JSON 格式的用户信息
          final userMap = jsonDecode(userInfoJson) as Map<String, dynamic>;
          developer.log('📝 Parsed user map: ${userMap.keys}', name: 'AuthViewModel');
          
          _currentUser = UserModel.fromJson(userMap);
          notifyListeners();
          developer.log('✅ User restored from storage: ${_currentUser?.username} (ID: ${_currentUser?.id})', name: 'AuthViewModel');
          
          // 恢复用户信息后，如果 WebSocket 未连接，则连接（应用重启后需要重新连接）
          try {
            if (_webSocketService?.status != LocalWebSocketStatus.connected) {
              await _webSocketService?.connect();
              developer.log('✅ WebSocket connected after restoring user', name: 'AuthViewModel');
            }
          } catch (e) {
            developer.log('⚠️ Failed to connect WebSocket after restoring user: $e', name: 'AuthViewModel');
            // WebSocket 连接失败不影响用户恢复，只记录日志
          }
        } catch (e, stackTrace) {
          developer.log('❌ Failed to parse user info: $e', name: 'AuthViewModel');
          developer.log('Stack trace: $stackTrace', name: 'AuthViewModel');
          // 解析失败，保持 _currentUser 为 null
          _currentUser = null;
          notifyListeners();
        }
      } else {
        developer.log('⚠️ User info is null or empty', name: 'AuthViewModel');
        _currentUser = null;
        notifyListeners();
      }
    } catch (e, stackTrace) {
      // 恢复失败，不影响登录状态
      developer.log('❌ Failed to restore user from storage: $e', name: 'AuthViewModel');
      developer.log('Stack trace: $stackTrace', name: 'AuthViewModel');
      _currentUser = null;
      notifyListeners();
    }
  }

  /// 更新用户信息
  Future<bool> updateUserProfile({
    String? name,
    String? phone,
    int? gender,
    String? abstractField,
    String? fileName,
  }) async {
    _isLoading = true;
    _errorMessage = null;
    notifyListeners();

    try {
      final response = await _authRepository.updateUserProfile(
        name: name,
        phone: phone,
        gender: gender,
        abstractField: abstractField,
        fileName: fileName,
      );

      _isLoading = false;

      if (response.success && response.data != null) {
        _currentUser = response.data;
        _errorMessage = null;
        notifyListeners();
        return true;
      } else {
        _errorMessage = response.message ?? '更新失败';
        notifyListeners();
        return false;
      }
    } catch (e) {
      _isLoading = false;
      _errorMessage = ErrorHandler.getErrorMessage(e);
      ErrorLoggerService.logError(e, context: 'UpdateUserProfile');
      notifyListeners();
      return false;
    }
  }

  void clearError() {
    _errorMessage = null;
    notifyListeners();
  }
}

